<template>
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    :loading="loading"
    icon="plus"
    v-if="!isFollowed"
    @click="onFollow"
    >关注</van-button
  >
  <van-button
    class="follow-btn"
    round
    size="small"
    :loading="loading"
    v-else
    @click="onFollow"
    >已关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user.js';

export default {
  name: 'FollowUser',
  data() {
    return {
      loading: false,
    };
  },
  model: {
    prop: 'isFollowed', // 默认为value
    event: 'update-is_followed', // 默认为input
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true,
    },
    userId: {
      type: [Number, String, Object],
      required: true,
    },
  },
  methods: {
    onFollow() {
      this.loading = true;
      if (!this.isFollowed) {
        addFollow(this.userId)
          .then((res) => {
            this.$emit('update-is_followed', !this.isFollowed);
            this.loading = false;
          })
          .catch((err) => {
            if (err.response && err.response.status === 400) {
              this.$toast('你不能关注你自己');
            } else {
              this.$toast('关注失败');
            }
            this.loading = false;
          });
      } else {
        deleteFollow(this.userId)
          .then((res) => {
            this.$emit('update-is_followed', !this.isFollowed);
            this.loading = false;
          })
          .catch(() => {
            this.$toast('取消失败');
            this.loading = false;
          });
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
